
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from haco.models import *
from haco.jsTime import *
import logging
import twython
from datetime import *


def twitBot( request):
    mes ="<html><head></head><body>"
    api = apimake()              
    t = api.getUserMentions(count="20")

    for e in t:
        q = Mention.all()
        q =q.filter('postUser',e['user']['screen_name'])
        q =q.filter('postText',e['text'])
        q =q.filter('postDate >=',datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9))

        if len(q):
            break
        else:
#            post(makeReply(e))
            directMessage(e['user']['screen_name'],makeReply(e))
            save(e)

    return HttpResponse( "OK")

def post(msg):
    api = apimake()
    api.updateStatus(msg)

def directMessage(user, msg):
    api = apimake()
    api.sendDirectMessage(user, msg)

def save( e):
    mention =Mention()
    mention.postUser =e['user']['screen_name']
    mention.postText =e['text']
    mention.postDate =datetime.strptime(e['created_at'], '%a %b %d %H:%M:%S +0000 %Y')+timedelta(hours=9)
    mention.put()
    
def makeReply( e):
    #parse text and generate reply text
    return "OK I'v got your message"
    

def apimake():
    return twython.setup(authtype="Basic",username="user",password="pass")
